#!/bin/bash

# 一键构建并上传到Diawi脚本
# 使用方法: ./build_and_upload.sh [platform]
# platform可以是: android, ios, all (默认)

set -e

# 加载配置
source "$(dirname "$0")/diawi_config.sh"

# 颜色输出
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m'

print_info() {
    echo -e "${BLUE}[INFO]${NC} $1"
}

print_success() {
    echo -e "${GREEN}[SUCCESS]${NC} $1"
}

print_warning() {
    echo -e "${YELLOW}[WARNING]${NC} $1"
}

print_error() {
    echo -e "${RED}[ERROR]${NC} $1"
}

# 显示横幅
show_banner() {
    echo ""
    echo "🚀 Flutter 应用自动化构建与上传"
    echo "=====================================/"
    echo "项目: $PROJECT_DISPLAY_NAME"
    echo "版本: $(get_version)"
    echo "时间: $(date '+%Y-%m-%d %H:%M:%S')"
    echo "====================================="
    echo ""
}

# 检查Flutter环境
check_flutter() {
    if ! command -v flutter &> /dev/null; then
        print_error "Flutter 未安装或不在 PATH 中"
        exit 1
    fi
    print_success "Flutter 环境检查通过"
}

# 检查项目
check_project() {
    if [ ! -f "pubspec.yaml" ]; then
        print_error "当前目录不是Flutter项目"
        exit 1
    fi
    print_success "Flutter项目检查通过"
}

# 构建Android
build_android() {
    print_info "🤖 开始构建Android应用..."
    
    # 清理并获取依赖
    flutter clean
    flutter pub get
    
    # 构建APK
    flutter build apk --$ANDROID_BUILD_MODE --target-platform $ANDROID_TARGET_PLATFORM
    
    if [ -f "$ANDROID_APK_PATH" ]; then
        local file_size=$(ls -lh "$ANDROID_APK_PATH" | awk '{print $5}')
        print_success "✅ Android APK构建成功 ($file_size)"
        return 0
    else
        print_error "❌ Android APK构建失败"
        return 1
    fi
}

# 构建iOS
build_ios() {
    if [[ "$OSTYPE" != "darwin"* ]]; then
        print_warning "⚠️  当前系统不是macOS，跳过iOS构建"
        return 1
    fi
    
    if [ ! -d "ios" ]; then
        print_warning "⚠️  iOS目录不存在，跳过iOS构建"
        return 1
    fi
    
    print_info "🍎 开始构建iOS应用..."
    
    # 构建iOS
    flutter build ios --$IOS_BUILD_MODE --no-codesign
    
    if [ -d "$IOS_APP_PATH" ]; then
        # 创建IPA包
        print_info "正在打包IPA..."
        mkdir -p "build/ios/Payload"
        cp -R "$IOS_APP_PATH" "build/ios/Payload/"
        
        cd "build/ios"
        zip -r "flutter_ai_base.ipa" "Payload" > /dev/null
        cd "../.."
        
        if [ -f "$IOS_IPA_PATH" ]; then
            local file_size=$(ls -lh "$IOS_IPA_PATH" | awk '{print $5}')
            print_success "✅ iOS IPA构建成功 ($file_size)"
            return 0
        else
            print_error "❌ iOS IPA打包失败"
            return 1
        fi
    else
        print_error "❌ iOS构建失败"
        return 1
    fi
}

# 上传到Diawi
upload_to_diawi() {
    local file_path=$1
    local platform=$2
    
    print_info "📤 上传$platform应用到Diawi..."
    
    if [ ! -f "$file_path" ]; then
        print_error "文件不存在: $file_path"
        return 1
    fi
    
    # 上传
    local comment=$(generate_comment "$platform")
    local response=$(curl -s -X POST \
        -F "token=$DIAWI_TOKEN" \
        -F "file=@$file_path" \
        -F "comment=$comment" \
        -F "wall_of_apps=$DIAWI_WALL_OF_APPS" \
        -F "find_by_udid=$DIAWI_FIND_BY_UDID" \
        "$DIAWI_UPLOAD_URL")
    
    # 解析响应
    local job_id
    if has_jq; then
        job_id=$(echo "$response" | jq -r '.job // empty')
    else
        job_id=$(echo "$response" | sed -n 's/.*"job":"\([^"]*\)".*/\1/p')
    fi
    
    if [ -z "$job_id" ] || [ "$job_id" = "null" ]; then
        print_error "❌ 上传失败"
        echo "$response"
        return 1
    fi
    
    print_success "✅ 上传成功，任务ID: $job_id"
    
    # 等待处理完成
    print_info "⏳ 等待Diawi处理..."
    local attempts=0
    local max_attempts=60
    
    while [ $attempts -lt $max_attempts ]; do
        sleep 5
        ((attempts++))
        
        local status_response=$(curl -s "$DIAWI_STATUS_URL?token=$DIAWI_TOKEN&job=$job_id")
        local status
        
        if has_jq; then
            status=$(echo "$status_response" | jq -r '.status // "unknown"')
        else
            if echo "$status_response" | grep -q '"status":2000'; then
                status="2000"
            elif echo "$status_response" | grep -q '"status":4000'; then
                status="4000"
            else
                status="processing"
            fi
        fi
        
        case $status in
            "2000")
                # 处理完成
                local link
                if has_jq; then
                    link=$(echo "$status_response" | jq -r '.link')
                else
                    link=$(echo "$status_response" | sed -n 's/.*"link":"\([^"]*\)".*/\1/p')
                fi
                
                print_success "🎉 $platform 应用处理完成！"
                echo ""
                echo "🔗 安装链接: $link"
                echo ""
                
                # 保存链接
                echo "$(date '+%Y-%m-%d %H:%M:%S') - $platform: $link" >> "$LINKS_FILE"
                
                # 如果是macOS，复制到剪贴板
                if [[ "$OSTYPE" == "darwin"* ]] && command -v pbcopy &> /dev/null; then
                    echo "$link" | pbcopy
                    print_info "📋 链接已复制到剪贴板"
                fi
                
                return 0
                ;;
            "4000")
                print_error "❌ $platform 应用处理失败"
                return 1
                ;;
            *)
                echo -n "."
                ;;
        esac
    done
    
    echo ""
    print_error "❌ $platform 应用处理超时"
    return 1
}

# 主函数
main() {
    local platform=${1:-"all"}
    
    show_banner
    
    # 环境检查
    check_flutter
    check_project
    
    if ! has_jq; then
        print_warning "⚠️  jq未安装，使用简单的JSON解析"
        install_jq_hint
        echo ""
    fi
    
    local success_count=0
    local total_count=0
    
    # 根据参数构建和上传
    case $platform in
        "android")
            ((total_count++))
            if build_android; then
                if upload_to_diawi "$ANDROID_APK_PATH" "Android"; then
                    ((success_count++))
                fi
            fi
            ;;
        "ios")
            ((total_count++))
            if build_ios; then
                if upload_to_diawi "$IOS_IPA_PATH" "iOS"; then
                    ((success_count++))
                fi
            fi
            ;;
        "all")
            # Android
            ((total_count++))
            if build_android; then
                if upload_to_diawi "$ANDROID_APK_PATH" "Android"; then
                    ((success_count++))
                fi
            fi
            
            # iOS
            if [[ "$OSTYPE" == "darwin"* ]]; then
                ((total_count++))
                if build_ios; then
                    if upload_to_diawi "$IOS_IPA_PATH" "iOS"; then
                        ((success_count++))
                    fi
                fi
            fi
            ;;
        *)
            print_error "未知平台: $platform"
            echo "支持的平台: android, ios, all"
            exit 1
            ;;
    esac
    
    # 总结
    echo ""
    echo "========================================="
    echo "📊 构建和上传总结"
    echo "========================================="
    echo "✅ 成功: $success_count/$total_count"
    
    if [ -f "$LINKS_FILE" ]; then
        echo "📋 所有链接已保存到: $LINKS_FILE"
    fi
    
    if [ $success_count -eq $total_count ] && [ $total_count -gt 0 ]; then
        print_success "🎉 所有操作完成！"
        exit 0
    else
        print_warning "⚠️  部分操作失败"
        exit 1
    fi
}

# 运行主函数
main "$@" 